package com.it.park.controller.admin;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.it.park.client.service.HomeLogoService;
import com.it.park.common.JsonObj;
import com.it.park.common.Page;
import com.it.park.constant.Constant;
import com.it.park.model.HomeLogo;
import com.it.park.util.file.FileUtil;

@Controller
@RequestMapping("/admin/home")
public class AdminHomeLogoController {

	@Autowired
	private HomeLogoService homeLogoService;
	
	private Page page = null;
	
	private String rootPath=Constant.ADMIN_PATH;


	@RequestMapping("listRows")
	@ResponseBody
	public Map<String,Object> listRows(HttpServletRequest request){
			int pageNow = Integer.parseInt(request.getParameter("page"));
			int rows = Integer.parseInt(request.getParameter("rows"));
			Map<String,Object> map_ = new HashMap<String, Object>();
			Integer total = homeLogoService.selectTotal(map_);
			page = new Page(page != null?pageNow:1,total,rows);
			map_.put("startPos", page.getStartPos());
			map_.put("pageSize", page.getPageSize());
			List<HomeLogo> list = homeLogoService.selectPagination(map_);
			Map<String,Object> map  =new HashMap<String, Object>();
			map.put("total", total);
			map.put("rows", list);
			return map;
	} 
	
	@RequestMapping("homeList")
	public String homeList(HttpServletRequest request){
			return rootPath+"home/homeList";
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("deleteById")
	@ResponseBody
	public JsonObj deleteById(Integer[] ids){
		JsonObj jsonObj  = new JsonObj();
		try {
			for (int i = 0; i < ids.length; i++) {
				homeLogoService.deleteByPrimaryKey(ids[i]);
			}
			jsonObj.setMessage("删除成功!");
			return jsonObj;
		} catch (Exception e) {
			e.printStackTrace();
			jsonObj.setMessage("删除失败!");
			jsonObj.setSuccess(false);
			return jsonObj;
		}
	}
	
	/**
	 * 添加
	 */
	@RequestMapping("saveOrEdit")
	public String saveOrEdit(MultipartFile file,HomeLogo homeLogo,HttpServletRequest request){
		if(!file.isEmpty()){
			try {
				InputStream is =  file.getInputStream();
				homeLogo.setCreateDate(new Date());
				homeLogo.setImgFile(FileUtil.getBytes(is));
				if(homeLogo.getId() != null){
					homeLogoService.updateByPrimaryKeySelective(homeLogo);
				}else{
					homeLogoService.insertSelective(homeLogo);
				}
			} catch (IllegalStateException e) {
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "redirect:homeList";
	}
	
}
